<?php

namespace Database\Seeders;

use App\Models\Reply;
use App\Models\User;
use App\Notifications\PostReplied;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class NotificationSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $replies = Reply::with(['user', 'parent.user', 'post.user', 'post.bar'])->get();

        if ($replies->isEmpty()) {
            $this->command->warn('没有回复数据，请先运行 ReplySeeder');
            return;
        }

        $this->command->info('开始创建通知数据...');

        $notificationCount = 0;

        DB::transaction(function () use ($replies, &$notificationCount) {
            foreach ($replies as $reply) {
                // 1. 通知帖子作者（如果回复者不是作者本人）
                if ($reply->post->user_id !== $reply->user_id) {
                    $postAuthor = User::find($reply->post->user_id);
                    if ($postAuthor) {
                        $postAuthor->notify(new PostReplied($reply, $reply->user));
                        $notificationCount++;
                    }
                }

                // 2. 如果是楼中楼回复，通知被回复的回复作者（如果回复者不是被回复者本人）
                if ($reply->parent_id && $reply->parent->user_id !== $reply->user_id) {
                    $parentReplyAuthor = User::find($reply->parent->user_id);
                    if ($parentReplyAuthor) {
                        $parentReplyAuthor->notify(new PostReplied($reply, $reply->user));
                        $notificationCount++;
                    }
                }
            }
        });

        $this->command->info("通知数据填充完成！");
        $this->command->info("共创建 {$notificationCount} 条通知");
    }
}
